package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Transactional
@Service(interfaceClass = CheckGroupService.class)
public class CheckGroupServiceImpl implements CheckGroupService {

        @Autowired
        private CheckGroupDao checkGroupDao;

        @Override
        public PageResult findPage(QueryPageBean queryPageBean) {

                Integer currentPage = queryPageBean.getCurrentPage();
                Integer pageSize = queryPageBean.getPageSize();
                String queryString = queryPageBean.getQueryString();

                PageHelper.startPage(currentPage, pageSize);
                Page<CheckGroup> page = checkGroupDao.findPage(queryString);

                PageResult pageResult = new PageResult(page.getTotal(), page.getResult());

                return pageResult;
        }

        @Override
        public void add(CheckGroup checkGroup,Integer[] checkitemIds) {

                checkGroupDao.add(checkGroup);
                Integer id = checkGroup.getId();
                setCheckGroupAndCheckItem(id,checkitemIds );
        }

        @Override
        public CheckGroup findById(Integer id) {
                CheckGroup checkGroup = checkGroupDao.findById(id);
                return checkGroup;
        }

        @Override
        public List<Integer> findCheckItemIdsByCheckGroupId(Integer id) {
               List<Integer> checkitemIds =  checkGroupDao.findCheckItemIdsByCheckGroupId(id);

               return checkitemIds;
        }

        @Override
        public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {

                checkGroupDao.edit(checkGroup);
                Integer id = checkGroup.getId();
                checkGroupDao.deleteAssociation(id);
                setCheckGroupAndCheckItem(id,checkitemIds );
        }

        public void setCheckGroupAndCheckItem(Integer id,Integer[] checkitemIds){

                for (Integer checkitemId : checkitemIds) {
                        Map<String,Integer> map = new HashMap<>();
                        map.put("checkgroupId", id);
                        map.put("checkitemId",checkitemId );
                        checkGroupDao.setCheckGroupAndCheckItem(map);
                }
        }
}
